using MultiAgentsClient.ChatDataStructures;
using MultiAgentsServer.Scripts.Shared;
using OpenAI.ObjectModels.RequestModels;

namespace MultiAgentsShared;

[Serializable]
public class ChatAgent
{
    public string Name = NameConsts.DefaultAgentName;
    public string gptModel = NameConsts.DefaultModelName;
    public ChatListContainer ChatListContainer = new();

#if BACKEND
    public ChatAgent()
    {
    }
#endif
    public ChatMessageData AddUserMessage(int messageId, int userId, string message, List<int>? historyMessagesIdList, int tokens, string userName, DateTime dateTime)
    {
        ChatMessageData chatMsgData = ChatMessageData.FromUser(messageId, userId, message, historyMessagesIdList, [], [], tokens, userName, dateTime);
        ChatListContainer.ChatList.Insert(0, chatMsgData);
        return chatMsgData;
    }

    public ChatMessageData AddSystemMessage(int id, int senderId, string systemMessage, List<int>? historyMessagesIdList, int tokens, DateTime dateTime)
    {
        ChatMessageData chatMsgData = ChatMessageData.FromSystem(id, senderId, systemMessage, historyMessagesIdList, tokens, dateTime);
        ChatListContainer.ChatList.Add(chatMsgData);
        return chatMsgData;
    }

    public ChatMessageData AddAssistantMsg(int Id, int senderId, string chatMsg, int tokens, string author, bool streamFinished, DateTime TimeAdded, List<int>? historyMessagesIdList, List<ToolCall> toolCalls)
    {
        ChatMessageData chatMsgData = ChatMessageData.FromAssistant(Id, senderId, chatMsg, historyMessagesIdList, tokens, author, streamFinished, TimeAdded, toolCalls);
        ChatListContainer.ChatList.Add(chatMsgData);
        return chatMsgData;
    }

    public ChatMessageData AddToolMsg(int Id, int senderId, string toolCallId, string toolCallResult, List<int>? historyMessagesIdList, int tokens, DateTime TimeAdded)
    {
        ChatMessageData chatMsgData = ChatMessageData.FromTool(Id, senderId, toolCallId, toolCallResult, historyMessagesIdList, tokens, TimeAdded);
        ChatListContainer.ChatList.Add(chatMsgData);
        return chatMsgData;
    }

    public string InResponseTo()
    {
        var lastMsgFirstChatList = ChatListContainer.ChatList.OrderByDescending(c => c.TimeAdded).ToList();
        var chatListString = "\n";
        chatListString += "~~~~~~~~~~~~~~~(In Response To)~~~~~~~~~~~\n";
        var firstChat = lastMsgFirstChatList[0];
        chatListString += $"    {{ [{firstChat.role}] | [{firstChat.TimeAdded}]:\n";

        chatListString += $"Message From {firstChat.author}:\n";
        chatListString += $" {firstChat.content}";

        if (firstChat.toolCalls != null)
        {
            foreach (var toolCall in firstChat.toolCalls)
            {
                chatListString += $"{{FuncCall -> {toolCall.FunctionCall.Name}}}, ";
            }
        }

        chatListString += "    },\n";
        chatListString += "~~~~~~~~~~~~~~~(In Response To)~~~~~~~~~~~\n";
        return chatListString;
    }
}
